﻿
using System.Security.Cryptography;

namespace Timo.Common.Extension;

/// <summary>
/// des加解密（假MD5）
/// </summary>
public static class DESEncryptHelper
{
    private static string default_key { get; set; } = "a2023?01";
    private static string default_iv { get; set; } = "b2023?01";

    /// <summary>
    /// DES加密
    /// </summary>
    /// <param name="str">需要加密的</param>
    /// <param name="key">密匙</param>
    /// <param name="iv">向量</param>
    /// <returns></returns>
    public static string DESEncrypt(this string str, string? key = null,string? iv = null)
    {
        var res = string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            return res;
        if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            key = default_key;
        if (string.IsNullOrEmpty(iv) || string.IsNullOrWhiteSpace(iv))
            iv = default_iv;
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.Default.GetBytes(str);
        des.Key = ASCIIEncoding.ASCII.GetBytes(key);// 密匙
        des.IV = ASCIIEncoding.ASCII.GetBytes(iv);// 初始化向量
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        res = Convert.ToBase64String(ms.ToArray());
        return res;
    }

    /// <summary>
    /// DES解密
    /// </summary>
    /// <param name="str">需要解密的</param>
    /// <param name="key">密匙</param>
    /// <param name="iv">向量</param>
    /// <returns></returns>
    public static string DESDecrypt(this string str, string? key = null,string? iv = null)
    {
        var res = string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            return res;
        if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            key = default_key;
        if (string.IsNullOrEmpty(iv) || string.IsNullOrWhiteSpace(iv))
            iv = default_iv;
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Convert.FromBase64String(str);
        des.Key = ASCIIEncoding.ASCII.GetBytes(key);
        des.IV = ASCIIEncoding.ASCII.GetBytes(iv);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        // 如果两次密匙不一样，这一步可能会引发异常
        cs.FlushFinalBlock();
        res = System.Text.Encoding.Default.GetString(ms.ToArray());
        return res;
    }

}